package com.shirley.netty.ssl.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Scanner;

public class SSLTcpClient {
    public static final String SERVER_HOST = "127.0.0.1";
    public static final int SERVER_PORT = 8811;

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new SSLTcpClientChannel(SERVER_HOST, SERVER_PORT));
            ChannelFuture channelFuture = bootstrap.connect(SERVER_HOST, SERVER_PORT).sync();
            System.out.println("Client started.");

            System.out.print("Input message: ");

            while (true) {

                Scanner reader = new Scanner(System.in);
                String input = reader.nextLine();
                if ("quit".equalsIgnoreCase(input)) {
                    break;
                }
                channelFuture.channel().writeAndFlush(input);
            }
            channelFuture.channel().close();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            workGroup.shutdownGracefully().sync();
        }

    }
}
